﻿using AutoMapper;
using DFGK.IRepository;
using DFGK.IService;
using DFGK_WMS.Model.Dto.YS;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace DFGK.Service
{
    public class StockService : BaseService, IStockService
    {
        private readonly IStockRepository _stockRepository;
        private readonly IUnitOfWork _unitOfWork;
        public StockService(IMapper mapper, IStockRepository stockRepository, IUnitOfWork unitOfWork) : base(mapper)
        {
            _stockRepository = stockRepository;
            _unitOfWork = unitOfWork;
        }

        public bool AddStockList(List<Stock> stocks, out string message)
        {

            message = string.Empty;
           

            foreach (var item in stocks)
            {
                try
                {
                    // 生成唯一ID
                    item.Id = YitIdHelper.NextId();

                    // 检查Code是否重复
                    var existingMaterial = _stockRepository.QueryIsEntityWhere(x => x.StockCode == item.StockCode);
                    if (existingMaterial != null)
                    {
                        message = $"{item.StockCode}编码已存在";
                        return false;
                    }

                    // 添加单条记录
                    _stockRepository.AddEntity(item);

                    // 提交事务
                    var result = _unitOfWork.SaveChangesEntity();
                    if (!result)
                    {
                        message = "提交失败，请重试";
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    message = $"添加失败：{ex.Message}";
                    // 记录异常日志
                    return false;
                }
            }

            return true;
            

        }
        #region 三级 级联
        //// 1. 获取所有仓库数据
        //List<Stock> allStocks = _stockRepository.GetAllEntityList();

        //// 2. 根据仓库编码过滤逻辑（保持原逻辑）
        //bool isProductWarehouse = !string.IsNullOrEmpty(WarehouseCode) && WarehouseCode.Contains("K01");
        //string productWarehouseCode = "01.04"; // 假设这是需要过滤的编码前缀

        //var filteredStocks = allStocks
        //    .Where(s => isProductWarehouse
        //        ? s.StockCode.StartsWith(productWarehouseCode)
        //        : !s.StockCode.StartsWith(productWarehouseCode))
        //    .ToList();
        //if (POMode!=null)
        //{
        //    if (POMode.Contains("VMI"))
        //    {
        //        filteredStocks = allStocks.Where(d => d.StockName.Contains("VMI仓")).ToList();
        //    }
        //}
        //// 3. 分离三级节点（基于点号数量）
        //// 一级节点：无点（如 "01"）
        //var level1Nodes = filteredStocks
        //    .Where(s => s.StockCode.Count(c => c == '.') == 0)
        //    .OrderBy(s => s.StockCode)
        //    .ToList();

        //// 二级节点：一个点（如 "01.1"）
        //var level2Nodes = filteredStocks
        //    .Where(s => s.StockCode.Count(c => c == '.') == 1)
        //    .ToList();

        //// 三级节点：两个点（如 "01.1.1"）
        //var level3Nodes = filteredStocks
        //    .Where(s => s.StockCode.Count(c => c == '.') == 2)
        //    .ToList();

        //// 4. 建立层级关系
        //// 一级 -> 二级
        //foreach (var level1 in level1Nodes)
        //{
        //    // 父节点编码前缀：如 "01."
        //    string parentPrefix = $"{level1.StockCode}.";
        //    level1.Children = level2Nodes
        //        .Where(l2 => l2.StockCode.StartsWith(parentPrefix))
        //        .OrderBy(l2 => l2.StockCode)
        //        .ToList();
        //}

        //// 二级 -> 三级
        //foreach (var level2 in level2Nodes)
        //{
        //    // 父节点编码前缀：如 "01.1."
        //    string parentPrefix = $"{level2.StockCode}.";
        //    level2.Children = level3Nodes
        //        .Where(l3 => l3.StockCode.StartsWith(parentPrefix))
        //        .OrderBy(l3 => l3.StockCode)
        //        .ToList();
        //}
        //return level1Nodes;
        #endregion
        public List<Stock> GetCascadeStockData(string? WarehouseCode, string? SPGroupCode, string? stockName, string? POMode, int pageIndex, int pageSize, out int totalCount)
        {
         

            var list = _stockRepository.GetEntityAlls();
           
            if (!string.IsNullOrEmpty(POMode) && POMode.Contains("VMI"))
            {
                list = list.Where(d => d.StockName.Contains("VMI"));
            }
            else
            {
                if (!string.IsNullOrEmpty(WarehouseCode))
                {
                    if (WarehouseCode.Contains("K01"))
                    {
                        list = list.Where(x => x.StockName == "立库");
                    }

                }
                list = list.Where(d => !d.StockName.Contains("VMI"));
            }

            if (!string.IsNullOrEmpty(stockName))
            {
                list = list.Where(d => d.StockName.Contains(stockName));
            }
            if (!string.IsNullOrEmpty(SPGroupCode))
            {
                list = list.Where(d => d.SPGroupCode.Contains(SPGroupCode));
            }

            var lists = _stockRepository.GetEntityAlls(list, pageIndex, pageSize, out totalCount, x => x.CreateDate, false);
            return lists.ToList();


        }




    }
}
